var remainMinutes = 5;//默认配置倒计时5分钟
var remainSeconds = remainMinutes * 60;
var timer = "";
var id = "";//当前座位id
var userId = "zhangqianfeng"; //当前用户id
var seatedFlag = false;//已入座标识  默认false"未入座"
$(function () {
	//初始化座位列表
	initSeatList();
	//点击开始排队,显示当前队列位置
	$(document).on("click", "#startQueue", function () {
		$.confirm("确认开始排队？", function () {
			//ajax查询当前排队情况  总的排队人数+1为当前排队位置
			$.ajax({
				type: "get",
				url: "json/queue.json",
				data: {},
				async: true,
				dataType: "json",
				success: function (res) {
					if (res.success) {
						//ajax 发送给后端当前排队信息
						$.ajax({
							type: "get",
							data: {
								"userId": userId
							},
							url: "json/postData.json",
							success: function (result) {
								console.log(result);
								if (result.success) {
									$("#noEmptySeat").find("#queueNumber").text("您排第" + (res.queueNumberTotal * 1 + 1) + "位").show().siblings().hide();
								} else {
									$.alert("排队出错，请稍后重试！")
								}
							}
						})
					} else {
						$.alert("查询信息出错，请稍后重试！")
					}
				}
			})

		})
	})
	//预约位置
	$("#seatDetail").on("tap", "li", function () {
		var _this = this;
		//判断是否已入座
		if (!seatedFlag) {
			if ($(this).hasClass("occupied")) {
				$.alert('当前座位已被占用，请选择未占用的位置！');
				return false;
			} else if ($(this).hasClass("mine")) {
				$.alert('您已经占过该位置，请勿重复占用！');
				return false;
			} else {
				var isOccupied = false; //是否已有占据的位置
				var mineLength = $("#seatDetail .mine").length;
				var mineIndex = "";//已占据位置的索引
				if (mineLength) {
					isOccupied = true;
					mineIndex = $("#seatDetail .mine").attr("data-index");
				} else {
					isOccupied = false;
				}
				//换座位，重新计时
				if (isOccupied) {
					var thisId = $(_this).attr("data-index");
					$.confirm("当前已占座位" + mineIndex + ",是否切换到新的座位" + thisId + "？", function () {
						id = $(_this).attr("data-index");
						postOccupySeat(function () {
							$.alert("已成功切换到新位置" + thisId + "号！");
							$(".mine").removeClass("mine");
							$(_this).addClass("mine");
							$("#queueStatus").show().siblings().hide();
							$("#queueStatus #userNumber").text(id);
							//$("#seatStatus").html('<small>您的座位号是<span id="userNumber">'+ id +'</span>，入座剩余时间：<a href="javascript:;"><i class="minutes">5</i>分<i class="seconds">0</i>秒</a></small>');
							clearInterval(timer);
							remainSeconds = remainMinutes * 60;
							countDown(remainSeconds);
							timer = setInterval("countDown(remainSeconds)", 1000);
						})
					});
				} else {
					postOccupySeat(function () {
						id = $(_this).attr("data-index");
						$.alert("占座成功,将为您保留五分钟！", function () {
							$(_this).addClass("mine");
							var remainNum = $(".remainNum").text();
							$(".remainNum").text(remainNum * 1 - 1);
							$("#queueStatus").show().siblings().hide();
							$("#queueStatus #userNumber").text(id);
							//$("#seatStatus").html('<small>您的座位号是<span id="userNumber">'+ id +'</span>，入座剩余时间：<a href="javascript:;"><i class="minutes">5</i>分<i class="seconds">0</i>秒</a></small>');
							clearInterval(timer)
							remainSeconds = remainMinutes * 60;
							countDown(remainSeconds);
							timer = setInterval("countDown(remainSeconds)", 1000);
						});
					})
				}
			}
		} else {
			$.alert("您当前已入座，请勿重复占座！");
			return false;
		}
	})
	//调用微信扫一扫接口  入座
	//这里暂时不调用接口，以点击的形式实现
	$("#scanQRcode").on("click", function () {
		if (seatedFlag) {
			$.alert("您当前已入座，请离座后再次预约并扫描入座！");
			return false;
		} else {
			$.modal({
				title: '输入座位号',
				text: `<div class="item-content">
				<div class="item-media"><i class="icon icon-form-name"></i></div>
				<div class="item-inner">
					<div class="item-input">
						<input id="currentSeat" autocomplete="off" type="text" placeholder="请输入座位号">
					</div>
				</div>
			</div>`,
				buttons: [
					{
						text: '取消',
						bold: true,
						onClick: function () {
							// $.alert('取消')
						}
					},
					{
						text: '确定',
						bold: true,
						onClick: function () {
							let QRcodeId = $('#currentSeat').val();
							//判断与已预约的号码是否一致
							if (QRcodeId != id) {
								$.alert("当前未预约此座位，请确认预约信息！")
							} else {
								//ajax发送入座信息到后端
								$.ajax({
									type: "get",
									url: "json/postData.json",
									data: {
										"id": id,
										"userId": userId
									},
									success: function (result) {
										if (result.success) {
											seatedFlag = true;
											clearInterval(timer);
											$("#seatLeave").find(".seatNumber").text(id)
											$("#seatLeave").show().siblings().hide();
											$("li[data-index='" + id + "']").addClass("seated");
											$.alert("入座成功！");
										}
									}
								})
							}

						}
					},
				]
			})

		}
	})
	//确认离座
	$(document).on("click", "#confirmLeave", function () {
		$.confirm("确认离开此位置？", function () {
			//ajax请求，发送该位置id到后端，释放位置
			$.ajax({
				type: "get",
				url: "json/postData.json",
				data: {
					"id": id,
					"userId": userId
				},
				success: function (result) {
					if (result.success) {
						initSeatList();
						id = "";
						seatedFlag = false;
						$(".seated").removeClass("seated");
					}
				}
			})
		})
	})

})

function formatClass(data) {
	var value = "";
	if (data) {
		value = "occupied";
	} else {
		value = "";
	}
	return value
}
//倒计时
function countDown(sec) {
	var timeArr = [];
	timeArr[0] = Math.floor(sec / 60);
	timeArr[1] = sec % 60;
	$("#queueStatus .minutes").text(timeArr[0]);
	$("#queueStatus .seconds").text(timeArr[1]);
	if (remainSeconds == 0) {
		clearInterval(timer);
		$(".mine").removeClass("mine");
		$("#seatStatus").show().siblings().hide()
		//$("#seatStatus").html('<a href="javascript:;"><small>剩余座位<span class="remainNum">0</span>个，点击下方选择座位</small></a>');
		$(".remainNum").text($(".remainNum").text() * 1 + 1);
	}
	remainSeconds--;
	return timeArr
}

function initSeatList() {
	//获取位置信息,初始化列表
	$.ajax({
		type: "get",
		url: "json/index.json",
		async: true,
		success: function (res) {
			console.log(res);
			if (res.success) {
				var str = '<ul class="rows clearfix">';
				$.each(res["data"], function (key, val) {
					console.log(val);
					if (key * 1 % 9 == 0) {
						str += `<li data-index="${key}" class="${formatClass(val)}">${key}</li></ul><ul class="rows clearfix">`;
					} else {
						str += `<li data-index="${key}" class="${formatClass(val)}">${key}</li>`;
					}
				})
				$("#seatDetail").html(str + '</ul>');
				$(".remainNum").text(res.remain);

				//满座状态栏显示"开始排队"按钮  隐藏座位状态
				if (res.remain == 0) {
					$("#noEmptySeat").show().siblings().hide();
				} else {
					$("#seatStatus").show().siblings().hide();
				}
			} else {
				$.alert("获取数据出错！");
			}
		}
	});
}
function postOccupySeat(callback) {
	//ajax 发送当前占座信息到后端
	$.ajax({
		type: "get",
		data: {
			"id": id,
			"userId": userId
		},
		url: "json/postData.json",
		success: function (result) {
			if (result.success) {
				if (callback) {
					callback()
				}
			} else {
				$.alert("手慢了，座位被别人占用了！")
			}
		}
	})
}
